package com.veer.shop.interceptor;

import java.io.BufferedReader;
import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.veer.shop.mapper.ApiLogMapper;
import com.veer.shop.pojo.ApiLog;
import com.veer.shop.utils.DateTimeUtil;

/**
 * 接口日志拦截器
 * 
 * @author WangBin
 * 2020年9月18日-下午5:29:25
 */
public class ApiLogInterceptor implements HandlerInterceptor {
	
	@Autowired
	private ApiLogMapper apiLogMapper;
	@Autowired
	ObjectMapper jackJsonMapper;
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		ApiLog apilog = new ApiLog();
		
		apilog.setApiPath(request.getRequestURI());
		apilog.setRemoteIp(request.getRemoteAddr());
		apilog.setParams(getRequestParams(request).replaceAll(" ", ""));
		apilog.setCreatedAt(DateTimeUtil.getDateTime());
		
		request.setAttribute("apilog", apilog);
		return true;
	}
	
	// 获取 post 请求数据
	private String getRequestParams(HttpServletRequest request) throws JsonProcessingException {
		if(request.getMethod().toLowerCase().equals("get")) {
			// get 请求
			return jackJsonMapper.writeValueAsString(request.getParameterMap());
		} else {
			// post 请求
			StringBuffer data = new StringBuffer();
			String line = null;
			BufferedReader reader = null;
			try {
				reader = request.getReader();
				while (null != (line = reader.readLine()))
					data.append(line);
			} catch (IOException e) {
			} finally {
			}
			
			return data.toString();
		}
	}
	
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub
		HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
	}
	
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// TODO Auto-generated method stub
		ApiLog apilog = (ApiLog)request.getAttribute("apilog");
		
		apiLogMapper.insert(apilog);
	}
}
